import { postDecisionFlowGenerateApiDoc, IPostDecisionFlowGenerateApiDocRes } from '@/api';
import { MciCard, MciButton, MciNotification, MciTable, MciTableColumn } from '@/components/base';
import { DownPDF } from '@/components/business/DownPDF';
import { ElForm, ElFormItem } from 'element-plus';
import { OnLine } from './component/OnLine';
import config from '@/config';
import './index.scss';

export default defineComponent({
  setup() {
    const route = useRoute();
    const formRef = ref<InstanceType<typeof ElForm>>();
    const currentData = ref<IPostDecisionFlowGenerateApiDocRes>({});
    const flowId = computed(() => {
      return route.query.flowId as string;
    });
    const urlPrefix = ref<string>(config.apiDomain);
    const dialogVisible = ref(false);
    const textParams = ref<object>({});
    const isDownPDF = ref(false);
    const textData = ref<array>([]);
    const docSource = ref<object>({});

    const copyResParams = (data: any) => {
      if (navigator.clipboard && data) {
        const placeholders = Object.keys(data);
        const goalText = urlPrefix.value + data.replace(/{[^}]*}/g, currentData.value!.decisionId?.toString());
        navigator.clipboard.writeText(goalText).then(() => {
          MciNotification.success('复制成功');
        });
      }
    };

    const onlineTest = () => {
      const goalText = urlPrefix.value + currentData.value!.path.replace(/{[^}]*}/g, currentData.value!.decisionId?.toString());
      dialogVisible.value = true;
      textParams.value = {
        decisionId: currentData.value!.decisionId,
        path: goalText,
        data: currentData.value.inputVars || []
      };
    };

    // 下载页面
    const downPage = () => {
      // window.print();
      isDownPDF.value = true;
      passParameter();
    };

    // 传递参数
    const passParameter = () => {
      textData.value = [{
        name: '决策id：',
        value: currentData.value?.decisionId || '--'
      }, {
        name: '决策流名称：',
        value: currentData.value?.flowName || '--'
      }, {
        name: '目录：',
        value: currentData.value?.categoryName || '--'
      }, {
        name: '调用路径：',
        value: currentData.value?.path || '--'
      }, {
        name: '异步调用路径：',
        value: currentData.value?.asyncPath || '--'
      }, {
        name: '描述：',
        value: currentData.value?.description || '--'
      }];
      docSource.value = [
        {
          title: '请求入参：',
          column: [{
            prop: 'varName',
            label: '变量名称'
          }, {
            prop: 'required',
            label: '是否必须'
          }, {
            prop: 'varType',
            label: '变量类型'
          }, {
            prop: 'varLabel',
            label: '字段描述'
          }, {
            prop: 'varScope',
            label: '变量路径'
          }],
          data: currentData.value.inputVars || []
        },
        {
          title: '返回参数：',
          column: [{
            prop: 'varName',
            label: '变量名称'
          }, {
            prop: 'varType',
            label: '变量类型'
          }, {
            prop: 'varLabel',
            label: '字段描述'
          }, {
            prop: 'varScope',
            label: '变量路径'
          }],
          data: currentData.value.outputVars || []
        }
      ]
    };

    onMounted(async () => {
      const data = await postDecisionFlowGenerateApiDoc({ flowId: flowId.value });
      document.title = data?.flowName ? `${data.flowName} - API文档` : 'API文档';
      if (!data) return;
      currentData.value = data;
    });

    return () => {
      return (
        <div style={{ width: 'calc(100% - 32px)', height: 'calc(100vh - 127px)' }} class="relative my-16" id="printAre">
          <MciCard class="w-full h-full" style={{ overflow: 'auto' }}>
            <div class="doc-create">
              <div class="flex justify-between">
                <h2 class="mb-20">API文档</h2>
                <MciButton type="primary" class="ml-12" onClick={() => downPage()}>
                  下载
                </MciButton>
                {isDownPDF.value && <DownPDF docSource={docSource.value} textData={textData.value} docName={document.title} title={'API文档'} />}
              </div>
              <ElForm ref={formRef} model={currentData.value}>
                <ElFormItem class="flex-1" label="决策id：" prop="decisionId">
                  <span>{currentData.value!.decisionId}</span>
                </ElFormItem>
                <ElFormItem class="flex-1" label="决策流名称：" prop="flowName">
                  <span>{currentData.value!.flowName}</span>
                </ElFormItem>
                <ElFormItem class="flex-1" label="目录：" prop="categoryName">
                  <span>{currentData.value!.categoryName}</span>
                </ElFormItem>
                <ElFormItem class="flex-1" label="调用路径：" prop="path">
                  <span>{currentData.value!.path}</span>
                  <MciButton type="primary" link={true} class="ml-12" onClick={() => copyResParams(currentData.value!.path)}>
                    复制
                  </MciButton>
                </ElFormItem>
                <ElFormItem class="flex-1" label="异步调用路径：" prop="asyncPath">
                  <span>{currentData.value!.asyncPath}</span>
                  <MciButton type="primary" link={true} class="ml-12" onClick={() => copyResParams(currentData.value!.asyncPath)}>
                    复制
                  </MciButton>
                </ElFormItem>
                <ElFormItem class="flex-1" label="描述：" prop="description">
                  <span>{currentData.value!.description || '--'}</span>
                </ElFormItem>
                <ElFormItem class="flex-1" label="接口调试：" prop="varType">
                  <MciButton type="primary" link={true} onClick={() => onlineTest()}>
                    在线执行
                  </MciButton>
                </ElFormItem>
              </ElForm>
              <div class="mt-12">
                <h4>请求入参：</h4>
                <MciTable
                  // maxHeight={235}
                  data={currentData.value.inputVars || []}
                  row-key="varName"
                  default-expand-all>
                  <MciTableColumn label="变量名称" prop="varName" />
                  <MciTableColumn label="是否必须" prop="required" />
                  <MciTableColumn label="变量类型" prop="varType" />
                  <MciTableColumn label="字段描述" prop="varLabel" />
                  <MciTableColumn label="变量路径" prop="varScope" />
                </MciTable>
              </div>
              <div class="mt-24">
                <h4>返回参数：</h4>
                <MciTable
                  // maxHeight={285}
                  data={currentData.value.outputVars || []}
                  row-key="varName"
                  default-expand-all>
                  <MciTableColumn label="变量名称" prop="varName" />
                  <MciTableColumn label="变量类型" prop="varType" />
                  <MciTableColumn label="字段描述" prop="varLabel" />
                  <MciTableColumn label="变量路径" prop="varScope" />
                </MciTable>
              </div>
            </div>
          </MciCard>
          <OnLine v-model={dialogVisible.value} params={textParams} />
        </div>
      );
    };
  }
});
